package com.geline.uploadfile.dao;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.DataSourceUtils;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 初始化数据表
 * @author: mengxin
 * @date: 2023/8/19 17:17
 */
@Slf4j
public class InitDDLRunner {

    public static final String API_TABLE = "sys_file";
    private DataSource dataSource;
    private String table;

    public InitDDLRunner(DataSource dataSource, String table){
        this.dataSource = dataSource;
        this.table = table;
    }

    public void execute() throws SQLException {
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("init.sql");
        String ddlStr = IoUtil.readUtf8(in);
        Connection conn = DataSourceUtils.doGetConnection(dataSource);
        Statement stat = conn.createStatement();
        //获取数据库表名
        ResultSet rs = conn.getMetaData().getTables(null, null, this.table, null);
        // 判断表是否存在，如果存在则什么都不做，否则创建表
        if( rs.next() ){
            log.info(">>>> find table : {} !", this.table);
            return;
        }
        if(StrUtil.isNotBlank(this.table)){
            ddlStr = ddlStr.replace(API_TABLE, this.table);
        }else {
            this.table = API_TABLE;
        }
        int ret = stat.executeUpdate(ddlStr);
        log.info("create table : {} = {}", this.table, ret);
    }
}
